package com.xiaofan.ct.producer.io;

import com.xiaofan.ct.common.bean.DataOut;

import java.io.*;

/**
 * 本地文件输出
 */
public class LocalFileDataOut implements DataOut {

    private PrintWriter writer = null;

    public LocalFileDataOut(String path) {
        setPath(path);
    }

    @Override
    public void setPath(String path) {
        try {
            writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void write(Object data) throws IOException {
        write(data.toString());
    }

    /**
     * 将字符串生成到文件当中
     *
     * @param data
     * @throws IOException
     */
    @Override
    public void write(String data) throws IOException {
        writer.println(data);

        // 写一条数据立即刷到文件当中
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        if (writer != null) writer.close();
    }
}
